package com.zmn.oms.business.impl.messageV1.baidu;

import org.apache.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.impl.messageV1.common.AbstractBaseMessage;
import com.zmn.oms.common.constant.MessageRuleIdConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.shop.OrderShop;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.shop.OrderShopService;
import com.zmn.saas.common.dro.app.UserBaiduRelationDRO;
import com.zmn.saas.dubbo.interfaces.app.AppRemoteService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 类描述： 百度消息
 *
 * @author yule
 * @date 2020/7/9 11:47
 */
public abstract class AbstractMessageSendBaidu extends AbstractBaseMessage {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Reference(version = com.zmn.saas.dubbo.constant.SaasDubboConsts.INTERFACE_VERSION, check = false)
    protected AppRemoteService appRemoteService;
    @Autowired
    protected OrderShopService orderShopService;
    @Autowired
    protected RedisManager redisManager;
    @Autowired
    protected OrderChangeRecordService orderChangeRecordService;

    /**
     * 获取用户百度OpenId
     *
     * @param orderId
     * @param userId
     * @param channelId
     * @return
     */
    protected String getBaiduUserOpenId(Long orderId, Long userId, Integer channelId) {
        UserBaiduRelationDRO baiduRelationDRO = getBaiduInfo(orderId, userId, channelId);
        if (Objects.isNull(baiduRelationDRO)) {
            return null;
        }
        return baiduRelationDRO.getOpenId();
    }

    /**
     * 获取用户百度信息
     *
     * @param orderId
     * @param userId
     * @param channelId
     * @return
     */
    protected UserBaiduRelationDRO getBaiduInfo(Long orderId, Long userId, Integer channelId) {
        ResponseDTO<UserBaiduRelationDRO> resp;
        try {
            logger.info("订单号【{}】获取百度信息 getUserBaiduInfoByUserIdAndChannelId 入参userId={},channelId={}", orderId, userId, channelId);
            resp = appRemoteService.getUserBaiduInfoByUserIdAndChannelId(userId, channelId);
            logger.info("订单号【{}】获取百度信息 getUserBaiduInfoByUserIdAndChannelId 出参{}", orderId, resp);
            if (!resp.isSuccess() || Objects.isNull(resp.getData())) {
                logger.info("订单号【{}】getUserBaiduInfoByUserIdAndChannelId 百度信息失败", orderId);
                return null;
            }
        } catch (Exception ex) {
            logger.error(String.format("订单号%s，获取百度信息 getUserBaiduInfoByUserIdAndChannelId接口异常了:%s", orderId, ex.getMessage()), ex);
            return null;
        }
        return resp.getData();
    }


    /**
     * 映射场景id
     *
     * @param orderId 领单：BD0101  上门：BD0121  完成：BD0241
     *                上述ID为用户登入注册百度小程序对消息节点授权的id，为固定值
     * @return
     */
    protected Map<Integer, String> listSceneIds(Long orderId) {
        // 优先获取redis 表单信息，为空再获取数据店铺表单信息
        String redisKey = String.format(RedisKeyConsts.BAIDU_SCENEIDS_REDIS_KEY, String.valueOf(orderId));
        String sceneIds = redisManager.get(redisKey);
        if (StringUtils.isBlank(sceneIds)) {
            String sceneIdJson = getSceneId(orderId);
            if (StringUtils.isBlank(sceneIdJson)) {
                return null;
            }
            sceneIds = sceneIdJson;
        }

        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(sceneIds);
        } catch (Exception e) {
            logger.info("工单号{},场景id json={}解析异常", orderId, sceneIds);
            logger.error(e.getMessage(), e);
            return null;
        }

        if (Objects.isNull(jsonObject)) {
            logger.info("工单号{},场景id 为空", orderId);
            return null;
        }

        String takeSceneId = jsonObject.getString("BD0101");// 领单
        String visitSceneId = jsonObject.getString("BD0121"); // 上门
        String completeSceneId = jsonObject.getString("BD0241"); // 完成

        Map<Integer, String> sceneIdMap = new LinkedHashMap();
        sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_TAKE, takeSceneId);
        sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_MASTER_VISIT, visitSceneId);
        sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_COMPLETE, completeSceneId);

        if (StringUtils.isNotBlank(takeSceneId)) {
            sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_ASSIGN, takeSceneId);
            sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_CANCEL, takeSceneId);
        } else if (StringUtils.isNotBlank(visitSceneId)) {
            sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_ASSIGN, visitSceneId);
            sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_CANCEL, visitSceneId);
        } else if (StringUtils.isNotBlank(completeSceneId)) {
            sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_ASSIGN, completeSceneId);
            sceneIdMap.put(MessageRuleIdConsts.ZMN_MSG_RULEID_CANCEL, completeSceneId);
        }
        return sceneIdMap;
    }

    /**
     * 获取多个场景id 字符串
     *
     * @param orderId
     * @return
     */
    protected String getSceneId(Long orderId) {
        //店铺信息
        OrderShop orderShop = orderShopService.findByKey(orderId);
        if (orderShop != null) {
            return orderShop.getSceneId();
        }
        return null;
    }


    /**
     * 处理百度消息参数
     *
     * @param orderWork
     * @param orderDetail
     * @param ruleId
     * @return
     */
    protected Map<String, String> handleBaiduParams(OrderWork orderWork, OrderDetail orderDetail, Integer ruleId) {
        Map<String, String> smsMap = new HashMap<>();
        // 分单消息处理（下单）
        if (Objects.equals(MessageRuleIdConsts.ZMN_MSG_RULEID_ASSIGN, ruleId)) {
            // 服务价格
            String totalAmountStr = "30元起";
            if (NumberUtil.isNotNullOrZero(orderWork.getTotalAmount())) {
                totalAmountStr = MoneyUtil.parseToYuan(orderWork.getTotalAmount()) + "元";
            }
            // 用户地址
            StringBuilder userAddressInfo = new StringBuilder();
            userAddressInfo.append(orderDetail.getProvinceName()).append(orderDetail.getCityName()).append(orderDetail.getCountyName())
                    .append(StringUtils.defaultString(orderDetail.getStreet())).append(StringUtils.defaultString(orderDetail.getAddress()));

            smsMap.put("order_amount", totalAmountStr);
            smsMap.put("order_address", userAddressInfo.toString());
        } else {
            if (NumberUtil.isNotNullOrZero(orderWork.getTotalAmount())) {
                smsMap.put("order_amount", String.format("%s元", MoneyUtil.parseToYuan(orderWork.getTotalAmount())));
                smsMap.put("page_amount", String.format("%s元", MoneyUtil.parseToYuan(orderWork.getTotalAmount())));
            }
        }

        if (Objects.equals(MessageRuleIdConsts.ZMN_MSG_RULEID_TAKE, ruleId)) {
            smsMap.put("order_status", "工程师已领单");
        }
        if (Objects.equals(MessageRuleIdConsts.ZMN_MSG_RULEID_MASTER_VISIT, ruleId)) {
            smsMap.put("order_status", "工程师已上门");
        }
        // 产品信息
        OrderProduct orderProduct = getProduct(orderWork.getOrderId());
        smsMap.put("order_id", String.valueOf(orderWork.getOrderId()));
        smsMap.put("product_name", orderProduct.getShowCategName());
        smsMap.put("remark", "请您对我们的服务进行监督反馈。客服电话：4000682260");

        smsMap.put("duty_time", DateUtil.toString(orderWork.getDutyTime(), "MM月dd日 HH时mm分"));
        smsMap.put("order_time", DateUtil.toString(orderWork.getReceiveTime(), "MM月dd日 HH时mm分"));

        if (Objects.nonNull(orderWork.getVisitTime())) {
            smsMap.put("visit_time", DateUtil.toString(orderWork.getVisitTime(), "MM月dd日 HH时mm分"));
        }
        if (StringUtils.isNotBlank(orderWork.getMasterName())) {
            smsMap.put("master_name", orderWork.getMasterName());
        }
        if (Objects.nonNull(orderWork.getCompleteTime())) {
            smsMap.put("complete_time", DateUtil.toString(orderWork.getCompleteTime(), "MM月dd日 HH时mm分"));
        }
        if (Objects.nonNull(orderWork.getCancelTime())) {
            smsMap.put("cancel_time", DateUtil.toString(orderWork.getCancelTime(), "MM月dd日 HH时mm分"));
            smsMap.put("cancel_reason", "您的订单已取消，期待下次为您服务。客服：4000682260");
        }

        return smsMap;
    }


}
